<!--
  * 实训室耗材领用
  *
  * @Author:    王俊权
  * @Date:      2024-11-08 13:31:03
  * @Copyright  🐂🐎bloc
-->
<template>
  <a-modal
      :title="form.id ? '编辑' : '添加'"
      :width="700"
      :open="visibleFlag"
      @cancel="onClose"
      :maskClosable="false"
      :destroyOnClose="true"
  >
    <a-form ref="formRef" :model="form" :rules="rules" :label-col="{ span: 5 }" >
        <a-form-item label="耗材代码"  name="materialCode">
          <a-input style="width: 100%" v-model:value="form.materialCode" placeholder="耗材代码" />
        </a-form-item>
        <a-form-item label="耗材名称"  name="materialId">
<!--          <a-input style="width: 100%" v-model:value="form.materialName" placeholder="耗材名称" />-->
          <FabricMaterialsSelect ref="fabricMaterialsSelect" placeholder="请选择耗材名称" width="100%" v-model:value="form.materialId"   @getItem="getMaterialValue" />
        </a-form-item>
        <a-form-item label="数量"  name="quantity">
          <a-input-number style="width: 100%" v-model:value="form.quantity" placeholder="数量" />
        </a-form-item>
        <a-form-item label="用途"  name="purpose">
<!--          <a-input style="width: 100%" v-model:value="form.purpose" placeholder="主要包括等" />-->
          <a-select style="width: 100%" v-model:value="form.purpose" placeholder="请选择用途" :options="purposeOptions.map(item => ({ value: item }))" >
            <template #dropdownRender="{ menuNode: menu }">
              <v-nodes :vnodes="menu" />
              <a-divider style="margin: 4px 0" />
              <a-space style="padding: 4px 8px">
                <a-input ref="inputRef" v-model:value="name" placeholder="请输入" />
                <a-button type="text" @click="addItem">
                  <template #icon>
                    <plus-outlined />
                  </template>
                 添加
                </a-button>
              </a-space>
            </template>
          </a-select>
        </a-form-item>
        <a-form-item label="备注"  name="remark">
          <a-textarea style="width: 100%" v-model:value="form.remark" placeholder="备注" />
        </a-form-item>
        <a-form-item label="领用人"  name="usageUser">
<!--          <a-input style="width: 100%" v-model:value="form.usageUser" placeholder="领用人" />-->
          <EmployeeSelect ref="employeeSelect" placeholder="请选择领用人" width="100%" v-model:value="form.usageUser"   />
        </a-form-item>
<!--        <a-form-item label="仓库管理员"  name="warehouseManager">-->
<!--&lt;!&ndash;          <a-input style="width: 100%" v-model:value="form.warehouseManager" placeholder="仓库管理员" />&ndash;&gt;-->
<!--          <EmployeeSelect ref="employeeSelect" placeholder="请选择仓库管理员" width="100%" v-model:value="form.actualWarehouseManager"   />-->
<!--        </a-form-item>-->
    </a-form>

    <template #footer>
      <a-space>
        <a-button @click="onClose">取消</a-button>
        <a-button type="primary" @click="onSubmit">保存</a-button>
      </a-space>
    </template>
  </a-modal>
</template>
<script setup>
import {reactive, ref, nextTick, toRefs, watch, defineComponent, onMounted} from 'vue';
  import _ from 'lodash';
  import { message } from 'ant-design-vue';
  import { SmartLoading } from '/@/components/framework/smart-loading';
  import { consumablesUsageApi } from '/@/api/business/consumables-usage/consumables-usage-api';
  import { smartSentry } from '/@/lib/smart-sentry';
  import EmployeeSelect from "/@/components/system/employee-select/index.vue";
  import FabricMaterialsSelect from "/@/components/mycomponents/fabricselect/index.vue";

  // ------------------------ 数据 ------------------------
  const fabricMaterialItem = ref();
  const name = ref();
  const inputRef = ref();
  const purposeOptions = ref(['实训耗材', '维修配件', '竞赛训练']);

  // ------------------------ 事件 ------------------------

  const emits = defineEmits(['reloadList']);

  // ------------------------ 显示与隐藏 ------------------------
  // 是否显示
  const visibleFlag = ref(false);

  function show(rowData) {
    Object.assign(form, formDefault);
    if (rowData && !_.isEmpty(rowData)) {
      Object.assign(form, rowData);
    }
    // 使用字典时把下面这注释修改成自己的字典字段 有多个字典字段就复制多份同理修改 不然打开表单时不显示字典初始值
    // if (form.status && form.status.length > 0) {
    //   form.status = form.status.map((e) => e.valueCode);
    // }
    visibleFlag.value = true;
    if(form.id){
      getMaterialInfo();
    }
    nextTick(() => {
      formRef.value.clearValidate();
    });
  }

  function onClose() {
    Object.assign(form, formDefault);
    visibleFlag.value = false;
  }

  // ------------------------ 表单 ------------------------

  // 组件ref
  const formRef = ref();

  const employeeSelect = ref();
  const defaultDepartmentForm = {
    managerId: undefined, //部门负责人
  };
  let formState = reactive({
    ...defaultDepartmentForm,
  });
  const formDefault = {
      id:undefined,
      materialCode: undefined, //耗材代码
      materialName: undefined, //耗材名称
      quantity: undefined, //数量
      purpose: undefined, //用途，主要包括实训耗材、维修配件、竞赛训练等
      remark: undefined, //备注
      trainingDepartment: undefined, //实训部
      usageUser: undefined, //领用人,
      actualUser:undefined,
      warehouseManager: undefined, //仓库管理员
      materialId:undefined,
  };

  let form = reactive({ ...formDefault });

  const rules = {
      materialCode: [{ required: true, message: '耗材代码 必填' }],
      materialId: [{ required: true, message: '耗材名称 必填' }],
      quantity: [{ required: true, message: '数量 必填' }],
      purpose: [{ required: true, message: '用途，主要包括实训耗材、维修配件、竞赛训练等 必填' }],
      remark: [{ required: true, message: '备注 必填' }],
      trainingDepartment: [{ required: true, message: '实训部 必填' }],
      usageUser: [{ required: true, message: '领用人 必填' }],
      warehouseManager: [{ required: true, message: '仓库管理员 必填' }],
  };

  // 点击确定，验证表单
  async function onSubmit() {
    try {
      await formRef.value.validateFields();
      save();
    } catch (err) {
      message.error('参数验证错误，请仔细填写表单数据!');
    }
  }
async function getMaterialInfo(){
  try{
    const res = await consumablesUsageApi.getMaterial(form.materialId);
    fabricMaterialItem.value = res.data;
  }catch (e) {
    smartSentry.captureError(e);
  }
}

  //获取选择数据
function getMaterialValue(value) {
  // console.log(value)
  fabricMaterialItem.value = {...value};
  form.materialCode = value.fabricMaterialCode;
}

watch(()=>form.quantity,(value)=>{
  // console.log('lyy',value,fabricMaterialItem.value)
  if(!fabricMaterialItem.value){
    return;
  }
  if(Number(form.quantity)> Number(fabricMaterialItem.value.quantity)){
   try{
     message.error('数量不能大于库存数量');
   }catch (e) {
     smartSentry.captureError(e);
   }finally {
     form.quantity=fabricMaterialItem.value.quantity;
   }
  }
})

const VNodes = defineComponent({
  props: {
    vnodes: {
      type: Object,
      required: true,
    },
  },
  render() {
    return this.vnodes;
  },
});

const addItem = e => {
  e.preventDefault();
  console.log('addItem');
  purposeOptions.value.push(name.value);
  name.value = '';
  setTimeout(() => {
    inputRef.value?.focus();
  }, 0);
};

  // 新建、编辑API
  async function save() {
    SmartLoading.show();
    const newForm={...form};
    try {
      if (form.id) {
        await consumablesUsageApi.update(newForm);
      } else {
        await consumablesUsageApi.add(newForm);
      }
      message.success('操作成功');
      emits('reloadList');
      onClose();
    } catch (err) {
      smartSentry.captureError(err);
    } finally {
      SmartLoading.hide();
    }
  }


  defineExpose({
    show,
  });
</script>
